package controllers.features;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.StringTokenizer;

import javax.swing.JButton;

import views.features.ChronologyView;
import core.User;
import core.database.DataBaseManager;

public class CalendarPanelController implements ActionListener {

	private ChronologyView view;
	private User user;
	public static CalendarPanelController instance;

	private CalendarPanelController(ChronologyView view, User u) {
		this.view = view;
		user = u;
		view.addActionListenerToTheDays(this);
	}

	public static CalendarPanelController newInstance(ChronologyView view,
			User u) {
		if (instance == null)
			instance = new CalendarPanelController(view, u);
		return instance;

	}

	@Override
	public void actionPerformed(ActionEvent e) {
		JButton b = (JButton) e.getSource();
		StringTokenizer st = new StringTokenizer(b.getName(), "/");
		StringBuilder sb = new StringBuilder();
		int year = Integer.parseInt(st.nextToken());
		sb.append("" + year + "-");
		int month = Integer.parseInt(st.nextToken());
		if (month < 10)
			sb.append("0" + month + "-");
		else
			sb.append("" + month + "-");
		int day = Integer.parseInt(st.nextToken());
		if (day < 10)
			sb.append("0" + day);
		else
			sb.append("" + day);
		String d = sb.toString();
		System.out.println(d);
		try {
			String[] r = DataBaseManager.getChronogy(d, user.getUsername());
			if (r == null) {
				r = new String[1];
				r[0] = "NON HAI GIOCATO NESSUN GIOCO IN QUESTO GIORNO >(\nAVRESTI DOVUTO ALLENARTI DI PIU' ;) ";
			}
			view.updateChronology(r);
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
	}

}
